<template>
  <el-dialog :title="isEdit ? '编辑试题' : '添加新试题'" v-model="visible" width="60%" :close-on-click-modal="false"
    @close="handleClose">
    <el-form :model="form" ref="formRef" :rules="rules" label-position="top">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="题型" prop="questionType">
            <el-select v-model="form.questionType" placeholder="请选择题型" @change="onTypeChange">
              <el-option label="单选题" value="single_choice"></el-option>
              <el-option label="多选题" value="multi_choice"></el-option>
              <el-option label="填空题" value="fill_blank"></el-option>
              <el-option label="简答题" value="short_answer"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="分值" prop="points">
            <el-input-number v-model="form.points" :min="0.5" :step="0.5" placeholder="题目分值"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="题号" prop="sequence">
            <el-input-number v-model="form.sequence" :min="1" placeholder="题目顺序号"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="题干内容" prop="content">
        <el-input type="textarea" :rows="3" v-model="form.content" placeholder="请输入题干..."></el-input>
      </el-form-item>

      <div v-if="isChoiceType">
        <el-divider>选项设置</el-divider>
        <div v-for="(option, index) in form.options" :key="index" class="option-row d-flex align-items-center mb-3">

          <span v-if="form.questionType === 'true_false'" class="flex-grow-1">{{ option.optionContent }}</span>

          <el-input v-else v-model="option.optionContent" class="me-3" placeholder="请输入选项内容"></el-input>

          <el-checkbox v-if="form.questionType === 'multi_choice'" v-model="option.isCorrect" :true-label="1"
            :false-label="0" @change="updateReferenceAnswer">正确</el-checkbox>

          <el-radio v-if="form.questionType === 'single_choice' || form.questionType === 'true_false'" :label="index"
            v-model="correctOptionIndex" @change="setCorrectOption(index)">正确</el-radio>

          <el-button v-if="form.questionType !== 'true_false'" type="danger" link @click="removeOption(index)"
            class="ms-3">删除</el-button>
        </div>

        <el-button v-if="form.questionType !== 'true_false'" type="primary" link @click="addOption">
          <i class="bi bi-plus-circle me-1"></i>添加选项
        </el-button>
      </div>

      <div v-if="!isChoiceType">
        <el-form-item label="参考答案" prop="referenceAnswer">
          <el-input type="textarea" :rows="2" v-model="form.referenceAnswer" placeholder="请输入参考答案..."></el-input>
        </el-form-item>
      </div>

      <el-form-item label="评分标准" prop="scoringCriteria">
        <el-input type="textarea" :rows="2" v-model="form.scoringCriteria" placeholder="请输入评分标准..."></el-input>
      </el-form-item>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEdit ? '保存修改' : '确认添加' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useExamStore } from '@/stores/exam.js'; // 1. 导入你的 exam store

const props = defineProps({
  modelValue: Boolean,
  examId: { type: [String, Number], required: true },
  questionData: { type: Object, default: null },
  currentTotalPoints: { type: Number, default: 0 },
  existingSequences: {
    type: Array,
    default: () => []
  }
});
const emit = defineEmits(['update:modelValue', 'success']);

// 2. 实例化 store
const examStore = useExamStore();

// --- 表单和状态 ---
const formRef = ref(null);
const submitting = ref(false);
const isEdit = computed(() => !!props.questionData);
const form = reactive({
  questionType: 'single_choice',
  content: '',
  points: 2.0,
  referenceAnswer: '',
  scoringCriteria: '',
  sequence: 1,
  options: []
});
const validateSequence = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('题号不能为空'));
  }
  // 获取正在编辑的题目的原始题号
  const originalSequence = isEdit.value ? props.questionData.examQuestion.sequence : null;

  // 检查新题号是否已存在，并且这个题号不等于它自己的原始题号
  if (props.existingSequences.includes(value) && value !== originalSequence) {
    callback(new Error('该题号已存在，请使用其他题号'));
  } else {
    callback(); // 校验通过
  }
};
const rules = {
  questionType: [{ required: true, message: '请选择题型', trigger: 'change' }],
  points: [{ required: true, message: '请输入分值', trigger: 'blur' }],
  content: [{ required: true, message: '请输入题干内容', trigger: 'blur' }],
  sequence: [
    { required: true, message: '请输入题号' },
    { validator: validateSequence, trigger: 'blur' }
  ]
};
const getNextAvailableSequence = () => {
  const sequences = new Set(props.existingSequences);
  let nextSequence = 1;
  while (sequences.has(nextSequence)) {
    nextSequence++;
  }
  return nextSequence;
};
// --- v-model 实现 ---
const visible = ref(props.modelValue);
watch(() => props.modelValue, (isOpening) => {
  if (isOpening) {
    // 每次打开弹窗时，先重置表单到初始状态
    visible.value = true;
    formRef.value?.resetFields();
    Object.assign(form, {
        questionType: 'single_choice',
        content: '',
        points: 2.0,
        referenceAnswer: '',
        scoringCriteria: '',
        sequence: 1,
        options: []
    });
    correctOptionIndex.value = null;

    // 然后根据是“编辑”还是“新建”来设置表单
    if (isEdit.value) {
      const q = props.questionData.examQuestion;
      const opts = props.questionData.options || [];
      Object.assign(form, {
        questionType: q.questionType,
        content: q.content,
        points: q.points,
        referenceAnswer: q.referenceAnswer,
        scoringCriteria: q.scoringCriteria,
        sequence: q.sequence,
        options: JSON.parse(JSON.stringify(opts))
      });
      // 触发表单类型的变更逻辑，以正确生成选项
      onTypeChange(); 
      // 回显正确答案
      updateReferenceAnswer();
      if (form.questionType === 'single_choice' || form.questionType === 'true_false') {
        const correctIndex = form.options.findIndex(opt => opt.isCorrect === 1);
        if (correctIndex !== -1) {
          correctOptionIndex.value = correctIndex;
        }
      }
    } else {
      form.sequence = getNextAvailableSequence();
      onTypeChange();
    }
  }
});
const handleClose = () => { emit('update:modelValue', false); };




// --- 初始化逻辑 ---
onMounted(() => {
  if (isEdit.value) {
    const q = props.questionData.examQuestion;
    const opts = props.questionData.options || [];
    Object.assign(form, {
      questionType: q.questionType,
      content: q.content,
      points: q.points,
      referenceAnswer: q.referenceAnswer,
      scoringCriteria: q.scoringCriteria,
      sequence: q.sequence,
      options: JSON.parse(JSON.stringify(opts)) // 深拷贝
    });
    if (form.questionType === 'single_choice') {
      const correctIndex = form.options.findIndex(opt => opt.isCorrect === 1);
      if (correctIndex !== -1) {
        correctOptionIndex.value = correctIndex;
      }
    }
  } else {
    form.sequence = getNextAvailableSequence();
    addOption();
    addOption();
  }
});

// --- 选项管理 ---
const isChoiceType = computed(() => ['single_choice', 'multi_choice', 'true_false'].includes(form.questionType));
const correctOptionIndex = ref(null);

const addOption = () => {
  form.options.push({ optionContent: '', isCorrect: 0, sequence: form.options.length + 1 });
};
const removeOption = (index) => {
  form.options.splice(index, 1);
  // 更新后续选项的 sequence
  form.options.forEach((opt, i) => { opt.sequence = i + 1; });
  // 新增：删除选项后也要更新答案
  updateReferenceAnswer(); 
};
const setCorrectOption = (selectedIndex) => {
  form.options.forEach((option, index) => {
    option.isCorrect = (index === selectedIndex) ? 1 : 0;
  });
  // 设置完 isCorrect 标志后，调用统一的更新函数
  updateReferenceAnswer();
};
const getOptionLabel = (sequence) => String.fromCharCode(64 + sequence);
const updateReferenceAnswer = () => {
  if (form.questionType === 'single_choice' || form.questionType === 'true_false') {
    const correctOption = form.options.find(opt => opt.isCorrect === 1);
    // 注意：判断题的参考答案依然是 'A' 或 'B'，后端可以根据这个来映射
    // 如果后端需要 'true'/'false' 字符串，可以在这里加个判断
    form.referenceAnswer = correctOption ? getOptionLabel(correctOption.sequence) : '';
  } else if (form.questionType === 'multi_choice') {
    // 多选题逻辑：找到所有正确答案，排序并用逗号拼接
    const correctAnswers = form.options
      .filter(option => option.isCorrect === 1)
      .map(option => getOptionLabel(option.sequence))
      .sort(); // 排序确保答案顺序一致，如 "A,C" 而不是 "C,A"
    form.referenceAnswer = correctAnswers.join(',');
  }
  // 其他题型手动输入 referenceAnswer，此处无需处理
};
const onTypeChange = () => {
  // 先清空旧数据
  form.options = [];
  form.referenceAnswer = '';
  correctOptionIndex.value = null;

  if (form.questionType === 'true_false') {
    // 如果是判断题，创建固定的“正确”和“错误”选项
    form.options.push(
      { optionContent: '正确', isCorrect: 0, sequence: 1 },
      { optionContent: '错误', isCorrect: 0, sequence: 2 }
    );
  } else if (isChoiceType.value) {
    // 如果是其他选择题，像以前一样创建两个空选项
    addOption();
    addOption();
  }
};

// =================================================================
//  核心修改在这里：实现 handleSubmit 函数
// =================================================================
const handleSubmit = async () => {
  try {
    // 1. 基础表单校验 (el-form 自带的)
    await formRef.value.validate();

    // 2. 新增：选择题的校验逻辑
    if (form.questionType === 'single_choice' || form.questionType === 'multi_choice') {
      if (form.options.length < 2) {
        ElMessage.error('单选或多选题至少需要两个选项！');
        return; // 中断提交
      }
      const hasEmptyOption = form.options.some(opt => !opt.optionContent || !opt.optionContent.trim());
      if (hasEmptyOption) {
        ElMessage.error('所有选项的内容都不能为空！');
        return; // 中断提交
      }
    }

    // 3. 新增：填空题和简答题的校验逻辑
    if (form.questionType === 'fill_blank' || form.questionType === 'short_answer') {
      if (!form.referenceAnswer || !form.referenceAnswer.trim()) {
        ElMessage.error('填空题或简答题的参考答案不能为空！');
        return; // 中断提交
      }
    }

    // 4. 分数校验 (已有逻辑)
    const pointsBeforeEdit = isEdit.value ? props.questionData.examQuestion.points : 0;
    if ((props.currentTotalPoints - pointsBeforeEdit + form.points) > 100) {
      ElMessage.error('操作失败！加上此题分数后，试卷总分将超过100分。');
      return;
    }

    // 5. 准备并发送数据 (已有逻辑)
    submitting.value = true;
    const payload = JSON.parse(JSON.stringify(form));
    if (!isChoiceType.value) {
      delete payload.options;
    }

    const handleSuccess = (response) => {
      ElMessage.success(isEdit.value ? '修改成功！' : '添加成功！');
      submitting.value = false;
      emit('success');
      handleClose();
    };

    const handleFailure = (message) => {
      submitting.value = false;
    };
    
    if (isEdit.value) {
      examStore.updateQuestion({
        questionId: props.questionData.examQuestion.id,
        questionData: payload
      }, handleSuccess, handleFailure);
    } else {
      examStore.addQuestionToExam({
        examId: props.examId,
        questionData: payload
      }, handleSuccess, handleFailure);
    }

  } catch (error) {
    console.log("表单校验失败", error);
    ElMessage.error("请检查表单项是否填写完整！");
  }
};
</script>